package com.freedom.util.usually;

import java.io.File;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.freedom.exception.RTServiceExcepton;

/**
 * 文件上传工具类
 * 
 * @author hgj
 *
 */
public class FileUploadUtil {

	/**
	 * spring提供的上传方式
	 * @param request
	 * @param path
	 * @return
	 * @throws RTServiceExcepton
	 */
	@SuppressWarnings("rawtypes")
	public static String uploadFiles(HttpServletRequest request, String path) throws RTServiceExcepton {
		try {
			// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				Iterator iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (null != file) { // 上传
						file.transferTo(new File(path+ file.getOriginalFilename()));
					}
					return file.getOriginalFilename(); // 表示成功，返回一个文件名
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return null;
	}

	public static boolean uploadTransferTo(CommonsMultipartFile file,String path) throws RTServiceExcepton {
		try {
			File targetFile = new File(path);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 通过CommonsMultipartFile的方法直接写文件
			file.transferTo(targetFile);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
